package extensions.com.beoui.geocell;


import java.util.Date;
import java.util.List;

import org.apache.commons.lang.time.DateUtils;

import play.Logger;
import siena.PersistenceManager;
import siena.Query;

import com.beoui.geocell.GeocellQueryEngine;
import com.beoui.geocell.model.GeocellQuery;

/**
 * 
 * Simple GeocellQueryEngine implementation to work with Siena API by using its
 * PersistenceManager to do simple proximity queries
 * 
 * @author Marc
 * 
 */
public class SienaGeocellQueryEngine implements GeocellQueryEngine {
	private PersistenceManager persistenceManager;

	public PersistenceManager getPersistenceManager() {
		return persistenceManager;
	}

	public void setPersistenceManager(PersistenceManager persistenceManager) {
		this.persistenceManager = persistenceManager;
	}

	@Override
	public <T> List<T> query(GeocellQuery q, List<String> args,
			Class<T> classType) {
		Logger.debug("Looking for geocell: %s", args.get(0));
		Query<T> query = this.persistenceManager.createQuery(classType);
		Date date = new Date();
		// TODO not harcoded...
		date = DateUtils.addMinutes(date, 10);
		return query.filter("geocells", args.get(0)).filter("time<", date).fetch();
	}

	public SienaGeocellQueryEngine(PersistenceManager persistenceManager) {
		super();
		this.persistenceManager = persistenceManager;
	}
}
